<template>
  <div :class="['sidebar', { collapsed }]">
    <div class="sidebar-header">
      <span v-if="!collapsed" class="sidebar-title">数据可视化</span>
      <div class="sidebar-toggle" @click="toggleSidebar" :class="{ rotated: !collapsed }">
        &raquo; <!-- Unicode 右箭头 -->
      </div>
    </div>

    <div v-if="!collapsed" class="sidebar-menu">
      <a class="nav-link" :class="{active: isFundOpen}" @click="toggleFund">
         基金
        <span class="toggle-icon" :class="{ rotated: isFundOpen }">&raquo;</span>
      </a>
      <div v-show="isFundOpen" class="submenu">
        <!-- Loop through fundCategories to create submenu links -->
        <a
          v-for="category in fundCategories"
          :key="category.type"
          class="nav-link sub-link"
          :class="{active: isActive(`/dashboard/fund/${category.path}`)}"
          @click="goTo(null, category.type, 'fund')"
        >
          {{ category.name }}
        </a>
      </div>
      <a class="nav-link" :class="{active: isIndexOpen}" @click="toggleIndex">
        指数
        <span class="toggle-icon" :class="{ rotated: isIndexOpen }">&raquo;</span>
      </a>
      <div v-show="isIndexOpen" class="submenu">
        <a
          v-for="category in indexCategories"
          :key="category.type"
          class="nav-link sub-link"
          :class="{active: isActive(`/dashboard/index/${category.path}`)}"
          @click="goTo(null, category.type, 'index')"
        >
          {{ category.name }}
        </a>
        <a
          class="nav-link sub-link"
          :class="{active: isActive('/dashboard/index/analysis')}"
          @click="goTo('/dashboard/index/analysis')"
        >
          智能分析
        </a>
      </div>
      <a
        class="nav-link"
        :class="{active: isActive('/dashboard/favorites')}"
        @click="goTo('/dashboard/favorites')"
      >
        自选
      </a>
    </div>
     <div v-else class="sidebar-menu-collapsed">
       <a class="nav-link-collapsed" :class="{active: isActive('/dashboard')}" @click="goTo('/dashboard')">总</a>
       <a class="nav-link-collapsed" :class="{active: isActive('/dashboard/fund') || route.path.startsWith('/dashboard/fund/')}" @click="toggleSidebar">基</a>
       <a class="nav-link-collapsed" :class="{active: isActive('/dashboard/index') || route.path.startsWith('/dashboard/index/')}" @click="toggleSidebar">指</a>
       <a class="nav-link-collapsed" :class="{active: isActive('/dashboard/favorites')}" @click="goTo('/dashboard/favorites')">自</a>
     </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

const collapsed = ref(false);
const isFundOpen = ref(false);
const isIndexOpen = ref(false);

// Define the list of fund categories
const fundCategories = [
  { name: '消费', type: '必需消费', path: 'consumption' },
  { name: '科技', type: '科技', path: 'science' },
  { name: '金融', type: '金融', path: 'finance' },
  { name: '医疗健康', type: '医疗健康', path: 'healthcare' },
  { name: '新能源与环保', type: '新能源与环保', path: 'newenergy' },
  { name: '周期大宗商品', type: '周期大宗商品', path: 'cyclecommodities' },
  { name: '房地产基建', type: '房地产基建', path: 'realestateinfrastructure' },
  { name: '国际区域', type: '国际区域', path: 'internationalregional' },
  { name: '新兴产业', type: '新兴产业', path: 'emergingindustries' },
  { name: '传统产业', type: '传统产业', path: 'traditionalindustries' },
];

const indexCategories = [
  { name: '沪深300', type: '沪深300', path: 'hushen300' },
  { name: '上证50', type: '上证50', path: 'sse50' },
  { name: '上证指数', type: '上证指数', path: 'shanghai_stock_exchange_index' },
  { name: '深证成指', type: '深证成指', path: 'shenzhen_component_index' },
  { name: '中证500', type: '中证500', path: 'zhongzheng500' },
  { name: '中证1000', type: '中证1000', path: 'zhongzheng1000' },
  { name: '中证A50', type: '中证A50', path: 'zhongzhenga50' },
];

const goTo = (path, type = null, menuType = 'fund') => {
  if (collapsed.value) {
    collapsed.value = false;
  }
  // Close all submenus before navigating to a new top-level section
  isFundOpen.value = false;
  isIndexOpen.value = false;

  if (type) {
    if (menuType === 'fund') {
      const category = fundCategories.find(c => c.type === type);
      router.push({ name: 'FundDashboardByType', params: { type: type, board: category.path } });
    } else if (menuType === 'index') {
      const category = indexCategories.find(c => c.type === type);
      router.push({ name: 'IndexDashboardByType', params: { type: type, board: category.path } });
    }
  } else if (path) {
    router.push(path);
  }
};

const isActive = (path) => {
    // Check if the current route path starts with the given path for nested routes
    if (path === '/dashboard') return route.path.startsWith('/dashboard'); // Check for any dashboard route
    // For fund categories, check if the route name is 'FundDashboardByType' and the type param matches
    if (route.name === 'FundDashboardByType' && path.endsWith(route.params.type)) {
        return true;
    }
    // Add check for the new Index Analysis page route
    if (path === '/dashboard/index/analysis') {
        return route.path === path;
    }
    // For Index Dashboard pages, check if the route name is 'IndexDashboardByType' and the board param matches
    if (route.name === 'IndexDashboardByType' && path.endsWith(route.params.board)) {
        return true;
    }
    // Add check for the new Favorites page route
    if (path === '/dashboard/favorites') {
        return route.path === path;
    }
    return route.path.startsWith(path);
};

const toggleSidebar = () => {
  collapsed.value = !collapsed.value;
  // Close submenus when collapsing sidebar
  if (collapsed.value) {
      isFundOpen.value = false;
      isIndexOpen.value = false;
  }
};

const toggleFund = () => {
   if (collapsed.value) {
    collapsed.value = false;
   }
   isFundOpen.value = !isFundOpen.value;
   // Close other menus
   isIndexOpen.value = false;
};

const toggleIndex = () => {
  if (collapsed.value) {
    collapsed.value = false;
  }
  isIndexOpen.value = !isIndexOpen.value;
  // Close other menus
  isFundOpen.value = false;
};

// Watch route changes to update active state and open fund/index submenus
watch(route, (newRoute) => {
  if (newRoute.path.startsWith('/dashboard/fund/')) {
    isFundOpen.value = true;
    isIndexOpen.value = false; // Close index menu when navigating to fund
  } else if (newRoute.path.startsWith('/dashboard/index/')) {
      isIndexOpen.value = true;
      isFundOpen.value = false; // Close fund menu when navigating to index
  } else if (newRoute.path === '/dashboard/favorites') { // Add check for favorites route
      isFundOpen.value = false; // Close fund menu
      isIndexOpen.value = false; // Close index menu
  } else if (newRoute.path === '/dashboard') { // Handle base dashboard route
      isFundOpen.value = false;
      isIndexOpen.value = false;
  }
}, { immediate: true });
</script>

<style scoped>
.sidebar {
  width: 240px; /* 默认展开宽度 */
  min-width: 60px; /* 最小收缩宽度 */
  background: #2c3e50; /* 深色背景 */
  color: #ecf0f1; /* 浅色文字 */
  height: 100vh;
  transition: width 0.3s ease-in-out; /* 收缩展开动画 */
  position: relative;
  overflow-y: auto; /* 内容多时滚动 */
  overflow-x: hidden;
  box-shadow: 2px 0 5px rgba(0,0,0,0.2);
  flex-shrink: 0; /* 不被主内容区挤压 */
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar-header {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #34495e;
    position: relative;
}

.sidebar-title {
    font-size: 1.2rem;
    font-weight: bold;
    flex-grow: 1; /* 占据剩余空间 */
    margin-right: 10px;
    white-space: nowrap; /* 防止文字换行 */
}

.sidebar-toggle {
  cursor: pointer;
  font-size: 1.5rem;
  color: #ecf0f1;
  transition: transform 0.3s ease-in-out; /* 旋转动画 */
  padding: 5px; /* 增加点击区域 */
}

.sidebar-toggle.rotated {
    transform: rotate(180deg); /* 展开时箭头向左 */
}

.sidebar-menu {
  padding: 10px 0;
}

.nav-link {
  display: flex; /* 使用flex布局对齐图标和文字 */
  align-items: center;
  color: #ecf0f1;
  padding: 12px 20px;
  text-decoration: none;
  border-left: 4px solid transparent; /* 默认无边框 */
  transition: background 0.2s, border-left-color 0.2s;
  font-size: 1rem;
  cursor: pointer;
}

.nav-link:hover {
  background: #34495e; /* hover背景色 */
}

.nav-link.active {
  background: #34495e; /* 激活背景色 */
  border-left-color: #4fc3f7; /* 激活左边框 */
  font-weight: bold;
}

.submenu {
  padding-left: 15px; /* 子菜单缩进 */
  border-left: 1px dashed #34495e; /* 子菜单连接线 */
  margin-left: 25px; /* 与父菜单左边框对齐 */
}

.sub-link {
    padding: 8px 20px; /* 子菜单padding */
}

.toggle-icon {
    margin-left: auto; /* 推到右边 */
    transition: transform 0.2s ease-in-out;
}

.toggle-icon.rotated {
    transform: rotate(90deg); /* 展开时旋转90度 */
}

/* 收缩状态下的菜单项样式 */
.sidebar.collapsed .nav-link,
.sidebar.collapsed .sidebar-header {
    justify-content: center;
    padding: 15px 0; /* 居中对齐，调整padding */
}

.sidebar.collapsed .sidebar-title,
.sidebar.collapsed .toggle-icon,
.sidebar.collapsed .submenu {
    display: none; /* 隐藏文字和子菜单 */
}

.nav-link-collapsed {
    display: block;
    text-align: center;
    padding: 12px 0; /* Adjusted padding for collapsed state */
    color: #ecf0f1;
    text-decoration: none;
    transition: background 0.2s;
    font-size: 1rem;
    cursor: pointer;
}

.nav-link-collapsed:hover {
    background: #34495e;
}

.nav-link-collapsed.active {
  background: #34495e; /* 激活背景色 */
  /* Removed left border for collapsed state */
  font-weight: bold;
}

.sidebar-menu-collapsed {
    /* Style for collapsed menu items */
    padding: 10px 0;
}

</style> 